package com.master.train.member.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.master.train.common.utils.JwtUtil;
import com.master.train.common.utils.PageUtils;
import com.master.train.common.utils.Query;
import com.master.train.member.dao.MemberDao;
import com.master.train.member.entity.MemberEntity;
import com.master.train.member.req.MemberLoginReq;
import com.master.train.member.resp.MemberLoginResp;
import com.master.train.member.service.MemberService;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void sengCode(MemberEntity member) {
        String mobile = member.getMobile();
//        查询号码是否已经注册
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<MemberEntity> eq = wrapper.eq("mobile", mobile);
        long count = this.count(eq);
        if(count>0){
            String code = RandomUtil.randomNumbers(4);
            System.out.println(code);
        }else {
            Snowflake snowflake = new Snowflake(1, 1);
            member.setId(snowflake.nextId());
            this.save(member);
            String code = RandomUtil.randomString(4);
            System.out.println("新用户"+code);

        }



    }

    @Override
    public MemberLoginResp login(MemberLoginReq member) {
        System.out.println("member="+member);
        MemberLoginResp resp = new MemberLoginResp();
        if (!"8888".equals(member.getCode())) {  // 使用equals方法比较字符串内容
            resp.setToken("error");
            System.out.println("验证码错误");
            return resp;
        }
            String mobile = member.getMobile();
//        查询号码是否已经注册
            QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
            QueryWrapper<MemberEntity> eq = wrapper.eq("mobile", mobile);
            MemberEntity memberDB = this.getOne(eq);
            resp.setId(memberDB.getId());
            resp.setMobile(memberDB.getMobile());
            System.out.println("memberDB="+memberDB);
            String token = JwtUtil.createToken(memberDB.getId(), memberDB.getMobile());
            resp.setToken(token);
            System.out.println("token="+token);

            return resp;



    }


}